package com.yt.server.mode.patterns.facade;

import org.springframework.stereotype.Component;

import com.yt.server.mode.api.ICommand;
import com.yt.server.mode.api.IFacade;
import com.yt.server.mode.api.INotification;
import com.yt.server.mode.api.IProxy;
import com.yt.server.mode.core.Controller;
import com.yt.server.mode.core.Model;
import com.yt.server.mode.patterns.observer.Notification;

/**
 * 核心控制
 */
@Component("Facade")
public class Facade implements IFacade {

	protected static Facade instance = null;

	/**
	 * 模型
	 */
	protected Model model = null;

	/**
	 * 控制器
	 */
	protected Controller controller = null;

	protected Facade() {
		instance = this;
		initializeFacade();
		System.out.println("Facade inited.");
	}

	protected void initializeFacade() {
		initializeModel();
		initializeController();
	}

	public synchronized static Facade getInstance() {
		if (instance == null)
			instance = new Facade();

		return instance;
	}

	protected void initializeController() {
		if (controller != null)
			return;
		controller = Controller.getInstance();
	}

	protected void initializeModel() {
		if (model != null)
			return;
		model = Model.getInstance();
	}

	public void registerCommand(ICommand command) {
		controller.registerCommand(command);
	}

	public void removeCommand(String notificationName) {
		this.controller.removeCommand(notificationName);
	}

	public boolean hasCommand(String notificationName) {
		return controller.hasCommand(notificationName);
	}

	public void registerProxy(IProxy proxy) {
		this.model.registerProxy(proxy);
	}

	public IProxy removeProxy(String proxyName) {
		if (this.model != null) {
			return this.model.removeProxy(proxyName);
		}
		return null;
	}

	public boolean hasProxy(String proxyName) {
		return model.hasProxy(proxyName);
	}

	public IProxy retrieveProxy(String proxyName) {
		return this.model.retrieveProxy(proxyName);
	}

	public void sendNotification(String notificationName, Object body,
			String type) {
		notifyObservers(new Notification(notificationName, body, type));
	}

	public void sendNotification(String notificationName, Object body) {
		sendNotification(notificationName, body, null);
	}

	public void sendNotification(String notificationName) {
		sendNotification(notificationName, null, null);
	}

	public void notifyObservers(INotification note) {
		if (controller != null)
			controller.notifyObservers(note);
	}
}